// pages/result/result.js
Page({
  data: {
    score: 0,
    totalQuestions: 0,
    correctAnswers: 0
  },
  onLoad: function() {
    const app = getApp();
    if (!app.globalData.isExamStarted || !app.globalData.examQuestions) {
      wx.navigateBack();
      return;
    }

    // 计算成绩
    const examQuestions = app.globalData.examQuestions;
    const userAnswers = app.globalData.userAnswers;
    let correctCount = 0;

    examQuestions.forEach(question => {
      const userAnswer = userAnswers[question.id];
      const correctAnswer = question.answer;

      // 检查答案是否正确
      if (Array.isArray(correctAnswer)) {
        // 多选题
        if (Array.isArray(userAnswer) && userAnswer.length === correctAnswer.length) {
          const isCorrect = userAnswer.every(option => correctAnswer.includes(option));
          if (isCorrect) {
            correctCount++;
          }
        }
      } else {
        // 单选题
        if (userAnswer === correctAnswer) {
          correctCount++;
        }
      }
    });

    // 计算分数 (答对题目数量 * 2)
    const score = correctCount * 2;

    this.setData({
      score: score,
      totalQuestions: examQuestions.length,
      correctAnswers: correctCount
    });

    // 重置考试状态
    app.globalData.isExamStarted = false;
  },
  restartExam: function() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  }
})